package xyz.hlh.boot3.service;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import xyz.hlh.boot3.annotation.MyAnno;
import xyz.hlh.boot3.entity.User;
import xyz.hlh.boot3.exception.MyException;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HLH
 * @description
 * @email 17703595860@163.com
 * @date Created in 2021/8/7 上午10:40
 */
@MyAnno
@Service
public class UserService {
    /** 模拟的用户列表 */
    private static final List<User> USER_LIST = new ArrayList<User>() {
        private static final long serialVersionUID = -7220237466804914720L;
        {
            add(new User(1, "zhangsan", "123", true));
            add(new User(2, "lisi", "456", true));
            add(new User(3, "wangwu", "789", true));
        }
    };
    /** 自增id的现有值 */
    private static int ID_NUM = 3;

    /**
     * 查询用户
     * @return 查询用户
     */
    public List<User> findAll() {
//        return USER_LIST;
        throw new MyException("aaa");
    }

    /**
     * 新增用户
     * @param user 要新增的用户信息
     * @return 新增完的用户
     */
    @MyAnno
    public User insertUser(User user) {
        user.setId(++ID_NUM);
        user.setEnable(true);
        USER_LIST.add(user);
        return user;
    }

    /**
     * 更新用户
     * @param user 要更新的用户信息
     * @return 更新完的用户
     */
    public User updateUser(User user, Integer userId) {
        // 判断参数
        if (userId == null) {
            throw new MyException("参数错误");
        }
        // 查找用户
        List<User> userList = USER_LIST.stream()
                .filter(user1 -> user1.getId().equals(userId) && user1.getEnable())
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(userList)) {
            throw new MyException("用户不存在");
        }
        // 赋值
        User realUser = userList.get(0);
        realUser.setUsername(user.getUsername());
        realUser.setPassword(user.getPassword());
        return realUser;
    }

    /**
     * 删除用户
     * @param userId 用户ID
     */
    public void deleteUser(Integer userId) {
        // 判断参数
        if (userId == null) {
            throw new MyException("参数错误");
        }
        // 删除
        USER_LIST.removeIf(user -> user.getId().equals(userId));
    }

}
